//
//  SWRegionPicker.swift
//  ChildStory
//
//  Created by linhan on 2017/1/16.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit

class SWRegionPicker: UIView,UIPickerViewDataSource,UIPickerViewDelegate,SWAPIComponent
{
    var cancelCallback:(()->Void)?
    //直辖市2级，其他3级
    var chooseCallback:((SWRegionItem, SWRegionItem, SWRegionItem)->Void)?
    
    private var _placeholder:SWRegionItem = SWRegionItem(title: "请选择", code: -1)
    private var _provinces:[SWRegionItem] = []
    private var _cities:[SWRegionItem] = []
    private var _districts:[SWRegionItem] = []
    
    private var _selectedProvince:SWRegionItem?
    private var _selectedCity:SWRegionItem?
    private var _selectedDistrict:SWRegionItem?
    
    
    
    lazy private var _confirmBtn:UIButton = UIButton(type: .system)
    lazy private var _pickview:UIPickerView = UIPickerView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        trace("DEINIT SWRegionPicker")
    }
    
    private func setup()
    {
        backgroundColor = UIColor.white
        
        let titleViewHeight:CGFloat = 40
        let titleView:UIView = UIView()
        titleView.frame = CGRectMake(0, 0, width, titleViewHeight)
        titleView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        addSubview(titleView)
        
        let cancelBtn:UIButton = UIButton(type: .system)
        cancelBtn.setTitleColor(UIColor.darkGray, for: .normal)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.sizeToFit()
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        cancelBtn.frame = CGRectMake(0, 0, cancelBtn.width, cancelBtn.height)
        addSubview(cancelBtn)
        
        let confirmBtn:UIButton = _confirmBtn
        confirmBtn.setTitleColor(UIColor.darkGray, for: .normal)
        confirmBtn.setTitle("确定", for: .normal)
        confirmBtn.sizeToFit()
        confirmBtn.isEnabled = false
        confirmBtn.addTarget(self, action: #selector(confirmBtnTapped), for: .touchUpInside)
        confirmBtn.frame = CGRectMake(width - confirmBtn.width, 0, confirmBtn.width, confirmBtn.height)
        addSubview(confirmBtn)
        
        _pickview.frame = CGRectMake(0, titleViewHeight, width, height - titleViewHeight)
        _pickview.dataSource = self
        _pickview.delegate = self
        _pickview.backgroundColor = UIColor(hex: 0xf9f9f9, alpha: 1)
        addSubview(_pickview)
        
        loadProvince()
    }
    
    private func loadProvince()
    {
        let req = SWProvinceFetchReq()
        req.successCallback = {[weak self] response,_ in
            if let provinces = (response as? SWProvinceFetchRsp)?.provinces,provinces.count > 0
            {
                if let strongSelf = self{
                    var data:[SWRegionItem] = [strongSelf._placeholder]
                    data += provinces.flatMap({SWRegionItem(response: $0)})
                    self?._provinces = data
                    self?._pickview.reloadComponent(0)
                    self?._pickview.selectRow(0, inComponent: 0, animated: true)
                }
            }
        }
        load(req)
    }
    
    private func loadCity(province:Int)
    {
        let req = SWCityFetchReq()
        req.province = province
        req.successCallback = {[weak self] response,_ in
            if let cities = (response as? SWCityFetchRsp)?.cities,cities.count > 0
            {
                if let strongSelf = self{
                    var data:[SWRegionItem] = [strongSelf._placeholder]
                    data += cities.flatMap({SWRegionItem(response: $0)})
                    self?._cities = data
                    self?._pickview.reloadComponent(1)
                    self?._pickview.selectRow(0, inComponent: 1, animated: true)
                }
                
            }
        }
        load(req)
    }
    
    private func loadDistrict(city:Int)
    {
        let req = SWDistrictFetchReq()
        req.city = city
        req.successCallback = {[weak self] response,_ in
            if let districts = (response as? SWDistrictFetchRsp)?.districts,districts.count > 0
            {
                if let strongSelf = self{
                    var data:[SWRegionItem] = [strongSelf._placeholder]
                    data += districts.flatMap({SWRegionItem(response: $0)})
                    self?._districts = data
                    self?._pickview.reloadComponent(2)
                    self?._pickview.selectRow(0, inComponent: 2, animated: true)
                }
                
            }
        }
        load(req)
    }
    
    private func itemsInComponent(_ component: Int) -> [SWRegionItem]
    {
        if component == 1
        {
            return _cities
        }
        else if component == 2
        {
            return _districts
        }
        else
        {
            return _provinces
        }
    }
    
    //MARK ================================= UIPickerViewDataSource =========================
    
    // returns the number of 'columns' to display.
    func numberOfComponents(in pickerView: UIPickerView) -> Int
    {
        return 3
    }
    
    //返回每个component的行数
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return itemsInComponent(component).count
    }
    
    //返回每个component对应行的标题
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    {
        return itemsInComponent(component).valueAt(row)?.title
    }
    
    //设定标题颜色
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?
    {
        if let title = self.pickerView(pickerView, titleForRow:row, forComponent:component)
        {
            let dic = [NSForegroundColorAttributeName:UIColor.darkGray]
            let attri:NSMutableAttributedString = NSMutableAttributedString(string: title, attributes: dic)
            return attri
        }
        return nil
    }
    
    //选中行
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if component == 0
        {
            _cities = []
            _districts = []
            _selectedProvince = nil
            _selectedCity = nil
            _selectedDistrict = nil
            _pickview.reloadComponent(1)
            _pickview.reloadComponent(2)
            
            if row > 0
            {
                if let item = _provinces.valueAt(row)
                {
                    _selectedProvince = item
                    loadCity(province: item.code)
                }
            }
            else
            {
                
            }
        }
        else if component == 1
        {
            _selectedCity = nil
            _selectedDistrict = nil
            _districts = []
            _pickview.reloadComponent(2)
            
            if row > 0
            {
                if let item = _cities.valueAt(row)
                {
                    _selectedCity = item
                    loadDistrict(city: item.code)
                }
            }
            else
            {
                
            }
        }
        else if component == 2
        {
            if let item = _districts.valueAt(row),row > 0
            {
                _selectedDistrict = item
            }
            else
            {
                _selectedDistrict = nil
            }
        }
        
        availabilityCheck()
    }
    
    private func availabilityCheck()
    {
        guard let province = _selectedProvince,
            let city = _selectedCity,
            let district = _selectedDistrict,
            province.code != -1 && city.code != -1 && district.code != -1 else{
            return
        }
        _confirmBtn.isEnabled = true
    }
    
    @objc private func confirmBtnTapped()
    {
        guard let province = _selectedProvince,
            let city = _selectedCity,
            let district = _selectedDistrict,
            province.code != -1 && city.code != -1 && district.code != -1 else{
                return
        }
        chooseCallback?(province, city, district)
    }
    
    @objc private func cancelBtnTapped()
    {
        cancelCallback?()
    }
    
}
